package at.markusreich.racecalendar.client.view;

import at.markusreich.racecalendar.client.model.CalendarEntry;
import at.markusreich.racecalendar.client.presenter.CalendarPresenter;
import at.markusreich.racecalendar.client.resources.CellTableCSS;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.cellview.client.ColumnSortEvent.AsyncHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Widget;

public class CalendarWidget extends Composite implements CalendarPresenter.Display {

	private CellTable.Resources cellTableCSS = GWT.create(CellTableCSS.class);

	private static CalendarWidgetUiBinder uiBinder = GWT.create(CalendarWidgetUiBinder.class);
	@UiField(provided = true)
	CellTable<CalendarEntry> cellTable = new CellTable<CalendarEntry>(10, cellTableCSS);
	@UiField
	HTMLPanel panel;

	interface CalendarWidgetUiBinder extends UiBinder<Widget, CalendarWidget> {
	}

	public CalendarWidget() {
		initWidget(uiBinder.createAndBindUi(this));

		// Create date column.
		TextColumn<CalendarEntry> dateColumn = new TextColumn<CalendarEntry>() {
			@Override
			public String getValue(CalendarEntry calendarEntry) {
				return calendarEntry.getDate().toString();
			}
		};

		// Make the name column sortable.
		dateColumn.setSortable(true);

		// Create name column.
		TextColumn<CalendarEntry> nameColumn = new TextColumn<CalendarEntry>() {
			@Override
			public String getValue(CalendarEntry calendarEntry) {
				return calendarEntry.getName();
			}
		};

		// Add the columns.
		cellTable.addColumn(dateColumn, "Datum");
		cellTable.addColumn(nameColumn, "Wettkampf");

		// Add a ColumnSortEvent.AsyncHandler to connect sorting to the
		// AsyncDataPRrovider.
		AsyncHandler columnSortHandler = new AsyncHandler(cellTable);
		cellTable.addColumnSortHandler(columnSortHandler);

		// We know that the data is sorted alphabetically by default.
		cellTable.getColumnSortList().push(nameColumn);
	}

	@UiHandler("panel")
	void onPanelAttachOrDetach(AttachEvent event) {
	}

	@Override
	public HasClickHandlers getList() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public CellTable<CalendarEntry> getCellTable() {
		return cellTable;
	}
}
